package com.sinosoft.weixin.shiro;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.sinosoft.weixin.controller.vo.Vo;
import org.apache.shiro.web.filter.authc.UserFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Shiro 中验证用户是否登入的拦截器
 *
 * Created by 胡正莹 on 2017/11/18.
 */
public class AutoDeployUserFilter extends UserFilter{
  private ObjectMapper objectMapper = new ObjectMapper();

  @Override
  protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
    HttpServletRequest req = (HttpServletRequest)request;
    String acceptHeader = req.getHeader("Accept");
    if(acceptHeader != null && acceptHeader.toLowerCase().contains("json")){
      HttpServletResponse resp = (HttpServletResponse)response;
      resp.setStatus(403);
      resp.addHeader("content-type", "application/json;charset=UTF-8");

      response.getWriter().println(objectMapper.writeValueAsString(Vo.fail("请先登入")));
      return false;
    }else{
      return super.onAccessDenied(request, response);
    }
  }
}